package com.erp.staobaotrasg.utils.m;

import android.os.Handler;
import android.widget.Toast;


import com.erp.staobaotrasg.YouZhuApplication;
import com.erp.staobaotrasg.utils.MLogUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.GZIPInputStream;

/**
 * Function: 网络数据 获取类
 * Created ： cfg
 * E-mail:   cfgnqk@sina.com
 * Created  on ：15-12-21
 */
public class MCHttpUtils {

    public static final int TYPE_TXT = 0;
    public static final int TYPE_IMG = 1;
    private static Handler mHandler = new Handler();
    private static ExecutorService service = Executors.newFixedThreadPool(10);

    /**
     * 构造方法私有化
     * 使其不能创建新的对象 保证唯一
     */
    private MCHttpUtils() {
    }

    /*****
     * post 方式获得服务器数据
     *
     * @param path 路径
     * @return
     * @throws IOException
     */
    public static InputStream getInputStreamByGet(String path) {
        InputStream inputStream = null;
        try {
            URL url = new URL(path);//URL
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开链接
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);// 从服务器获取数据；
            //  urlConnection.setDoOutput(true);// 往服务器写入数据
            int resposeCode = urlConnection.getResponseCode();//获得服务器响应码
            if (resposeCode == 200) {
                inputStream = urlConnection.getInputStream();//打开
                return inputStream;
            }
        } catch (IOException e) {
        }


        return inputStream;

    }

    /*****
     * post 方式获得服务器数据
     *
     * @param path   路径
     * @param params 提交内容
     * @param encode 字符编码
     * @return
     * @throws IOException
     */
    public static InputStream getInputStreamByPost(String path, Map<String, String> params, String encode) throws Exception {

        InputStream inputStream = null;

        StringBuffer buffer = new StringBuffer();
        if (params != null && !params.isEmpty()) {//判断 提交内容 不为空
            for (Map.Entry<String, String> entry : params.entrySet()) {//将 集合转换为提交格式
                buffer.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            buffer.deleteCharAt(buffer.length() - 1);// 最后多了一个字符& 删除最后一个字符

            MLogUtils.d("getStringByPostToPull", buffer.toString());
            URL url = new URL(path);//URL
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//打开链接
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);// 从服务器获取数据；
            urlConnection.setDoOutput(true);// 往服务器写入数据
            // 设置请求体的类型是文本类型 表示当前的提交的数据为 纯文本类型 不包括 二进制媒体数据
            // java 访问底层 不是基于浏览器访问 所以要写入http协议  写入提交格式
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            byte[] date = buffer.toString().getBytes(encode);// 设置编码转换格式
            urlConnection.setRequestProperty("Content-Length", String.valueOf(date.length));//内容长度
            OutputStream outputStream = urlConnection.getOutputStream();//打开写出流  将数据提交 写入到服务器
            outputStream.write(date, 0, date.length);//写入数据
            int resposeCode = urlConnection.getResponseCode();//获得服务器响应码
            MLogUtils.d("getStringByPostToPull", "----getInputStreamByPost---****" + resposeCode);
            if (resposeCode == 200) {
                inputStream = urlConnection.getInputStream();//打开
                //进行  gzip 是否压缩判断
                String headerFieldencoding = urlConnection.getHeaderField("Content-Encoding");
                if ("gzip".equals(headerFieldencoding)) {
                    inputStream = new GZIPInputStream(inputStream);/// 重新赋值

                }
                return inputStream;
            } else {
                Toast.makeText(YouZhuApplication.getInstance(), "数据请求异常，请检查网络", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(YouZhuApplication.getInstance(), "数据请求异常，请检查网络", Toast.LENGTH_SHORT).show();
        }

        return inputStream;

    }

    public static void getStringByPost(final String path, final HashMap<String, String> params, final MCHttpCallBackString callback) {

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream inputStream = getInputStreamByPost(path, params, "utf-8");

                    if (inputStream != null && inputStream.available() > 0) {
                        byte[] buffer = new byte[10 * 1024];
                        int len = -1;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final byte[] bytes = baos.toByteArray();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.response(new String(bytes));
                            }
                        });
                        inputStream.close();
                        buffer = null;// 清空内存
                        baos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /***
     * 在PullTorefreshListView 中使用 延迟1.5秒再进行加载数据
     *
     * @param path
     * @param params
     * @param callback
     */
    public static void getStringByPostToPull(final String path, final HashMap<String, String> params, final MCHttpCallBackString callback) {

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream inputStream = getInputStreamByPost(path, params, "utf-8");

                    if (inputStream != null && inputStream.available() > 0) {
                        byte[] buffer = new byte[10 * 1024];
                        int len = -1;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final byte[] bytes = baos.toByteArray();
                        Thread.sleep(1000); //睡眠 1.5 s 之后再进行加载数据
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.response(new String(bytes));
                            }
                        });
                        inputStream.close();
                        buffer = null;// 清空内存
                        baos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /***
     * 在PullTorefreshListView 中使用 延迟1.5秒再进行加载数据
     *
     * @param path
     * @param params
     * @param callback
     * @param delay    判断是否含有延迟加载的属性
     */
    public static void getStringByPostToPull(final String path, final HashMap<String, String> params, final MCHttpCallBackString callback, final boolean delay) {

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream inputStream = getInputStreamByPost(path, params, "utf-8");

                    if (inputStream != null) {
                        byte[] buffer = new byte[10 * 1024];
                        int len = -1;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final byte[] bytes = baos.toByteArray();
                        if (delay) {// 有延迟的 则进行1.5 s的睡眠
                            Thread.sleep(1500); //睡眠 1.5 s 之后再进行加载数据
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callback.response(new String(bytes));
                                }
                            });
                        } else {  // 没有 延迟的加载
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callback.response(new String(bytes));
                                }
                            });
                        }

                        inputStream.close();
                        buffer = null;// 清空内存
                        baos.close();
                    }

                } catch (Exception e) {
                    //   callback.complete();
                    MLogUtils.e("inputStream", "---" + e.getMessage());
                    e.printStackTrace();
                }
            }
        });
        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    callback.complete();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    public static void getImageByGet(final String path, final MCHttpCallBack callback) {

        service.execute(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = getInputStreamByGet(path);
                try {
                    if (inputStream != null && inputStream.available() > 0) {
                        byte[] buffer = new byte[10 * 1024];
                        int len = -1;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final byte[] bytes = baos.toByteArray();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.response(path, bytes);
                            }
                        });
                        inputStream.close();
                        buffer = null;// 清空内存
                        baos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
